import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:fluttertoast/fluttertoast.dart';

class DiaRoute extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return DioRouteState();
  }
}

Future _dioGitData() async {
  Dio dio = Dio(BaseOptions(
    baseUrl: 'https://api.github.com',
    headers: {
      HttpHeaders.acceptHeader: "application/vnd.github.v3+json,"
          "application/vnd.github.symmetra-preview+json",
    },
  ));

  Map<String, int> queryParameters = {
    'page': 1,
    'per_page':20,
  };

  String basic =
      'Basic ' + base64.encode(utf8.encode('1170184770@qq.com:zc1170184770'));

  return dio.get("/user/repos",
      options: Options(headers: {HttpHeaders.authorizationHeader: basic}));
}

void _save(String content) async {
  var path = await getExternalStorageDirectory();
  String filePath = '${path.path}/flutter.txt';
  File file = File(filePath);
  file.writeAsString(content).then((onValue) {
    Fluttertoast.showToast(msg: '保存成功');
  });
}

class DioRouteState extends State<DiaRoute> {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text('Dio'),
      ),
      body: FutureBuilder(
        future: _dioGitData(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            print(snapshot.error);
            _save(snapshot.data.toString());
            return SingleChildScrollView(
              child: Text(snapshot.data.toString()),
            );
          } else {
            return CircularProgressIndicator();
          }
        },
      ),
    );
  }
}
